<?php

namespace model;

class log_sql
{
    const TABLE = "log_sql";
    const TABLE_USER = "admin_user";

    public function insertData($dothing, $userid = null)
    {
        $pdo = \libs\pdo::Init();
        $prefix = $pdo->GetConfig();
        $table = $prefix['prefix'] . self::TABLE;

        $data = [
            'userid' => LoginUserInfo('userid') ?? $userid,
            'loginip' => GetIp(),
            'ca' => ROUTE['ctrl'] . '/' . ROUTE['act'],
            'useragent' => $_SERVER['HTTP_USER_AGENT'], //用户浏览器信息
            'time' => date('Y-m-d H:i:s', time()),
            'dothing' => $dothing,
        ];

        // 使用量小的系统可以打开这里，使用频率高的，不建议打开
        //只保留5000条数据
        // $count = $pdo->QueryOne("SELECT COUNT(*) as totle from {$table}");
        // if ($count['totle'] > 4999)
        //     $pdo->Submit("DELETE from {$table} order by id asc LIMIT 1");

        //写入数据库
        $sqlInsert = "INSERT INTO {$table} (userid, ca, loginip, useragent, time, dothing) VALUES ('{$data["userid"]}', '{$data["ca"]}', '{$data["loginip"]}', '{$data["useragent"]}', '{$data["time"]}', '{$data["dothing"]}')";
        $pdo->Submit($sqlInsert);
    }


    public function clearData()
    {
        //只有超级管理员能清除日志
        if (LoginUserInfo('gid') == 1) {
            $pdo = \libs\pdo::Init();
            $prefix = $pdo->GetConfig();
            $table = $prefix['prefix'] . self::TABLE;
            $pdo->Submit("TRUNCATE {$table}");
            SqlLog("清空了数据库操作日志！！！");
            return ['status' => 1, 'msg' => '操作成功'];
        } else
            return ['status' => 0, 'msg' => '你无权清除日志！'];
    }

    //获取数据并分页
    public function jsonPageSelect()
    {
        $db = \libs\db::Init();
        $p = intval($_GET['page'] ?? 0) ?: 1;
        $num = intval($_GET['limit'] ?? 0) ?: 15;
        $page = ['num' => $num, 'p' => $p, 'return' => true];

        $field = 'b.id as uid,b.username,b.nickname,a.*';
        $join[] = 'LEFT JOIN ' . self::TABLE_USER . ' b ON a.userid=b.id';

        //非超级管理员 只显示自己的内容
        if (LoginUserInfo('gid') != 1)
            $where['a.userid'] = LoginUserInfo("userid");

        if (isset($_GET['username'])) {
            $where['b.username LIKE'] = '%' . $_GET['username'] . '%';
        }

        return [
            'data' => $db->table(self::TABLE . ' a')->where($where)->field($field)->join($join)->Page($page)->order('a.id DESC')->select(),
            'page' => $db->getPage()
        ];
    }
}
